const express = require("express");
const md5 = require("blueimp-md5")
var User = require('./curd.js');
const Teacher = require("./teacher.js");
const Student = require("./student.js");
const router = express.Router();

router.post("/user/register", function (req, res) {
    var body = req.body;
    // console.log(body);
    User.find({
        $or: [
            {
                username: body.username
            },
            {
                nickname: body.nickname
            },
            {
                password: body.password
            }
        ]
    }, (err, data) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "server error register"
            })
        }
        if (data.length !== 0) {
            return res.status(200).json({
                code: 4000,
                flag: false,
                message: "账号或昵称已存在"
            })

        }
        body.token = md5(md5(body.username) + "b0352");
        new User(body).save(function (err, data) {
            if (err) {
                // return res.status(500).send("存储失败")
                return res.status(500).json({
                    code: 3000,
                    flag: false,
                    message: "server error,存储失败"
                })
            }
            //存储成功，提示注册成功
            // console.log("ok");
            // req.session.user = data;
            return res.json({
                "code": 2000,
                "flag": true,
                "message": "注册成功"
            })
        })
    })
});
router.post("/user/login", function (req, res) {
    const body = req.body;
    // console.log(req.body);
    //找数据库里是否存在， 存在才能登录
    User.findOne({
        username: body.username,
        password: body.password
    }, function (err, data) {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "server error login"
            })
        }
        if (!data) {
            return res.status(200).json({
                code: 4000,
                flag: false,
                message: "账号或密码错误"
            })
        }
        //如果上面两个判断都进不去，说明找到数据了
        // req.session.user = data;

        return res.status(200).json({
            "code": 2000,
            "flag": true,
            "message": "登录成功",
            "data": {
                "token": data.token
            }
        })
    })
});
router.get("/user/info", function (req, res) {
    var body = req.query;
    // console.log(body);
    User.findOne({
        token: body.token

    }, function (err, data) {
        // console.log(data);
        if (err) {
            return res.status(500).json({
                code: 3000,
                flag: false,
                message: "server error"
            })
        }
        if (!data) {
            return res.status(200).json({
                code: 4000,
                flag: false,
                message: "token不存在"
            })
        }
        //如果上面两个判断都进不去，说明找到数据了
        // req.session.user = data;

        return res.json({
            "code": 2000,
            "flag": true,
            "message": "成功获取用户信息",
            "data": {
                "nickname": data.nickname,
                "id": data._id
            }
        })
    })
});
//退出登录
router.post("/user/logout", function (req, res) {
    var body = req.body;
    User.findOne({
        token: body.token
    }, function (err, data) {
        if (err) {
            return res.status(500).json({
                code: 3000,
                flag: false,
                message: "server error"
            })
        }
        if (!data) {
            return res.status(200).json({
                code: 4000,
                flag: false,
                message: "token不存在"
            })
        }
        return res.status(200).json({
            "code": 2000,
            "flag": true,
            "message": "退出成功"
        })
    })
});
//获取所有教师列表
router.get("/teacher/list", function (req, res) {
    Teacher.find({}, function (err, data) {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "serve error getTeacherList"
            });
        }
        //数据总共多少条
        let count = data.length;
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: "查询成功",
            data: {
                total: count,
                rows: data
            }
        })
    })
})
//获取所有教师列表，带分页功能
router.post('/teacher/list', (req, res) => {
    let page = req.body.page || 1
    let size = req.body.size || 10
    let searchMap = req.body.searchMap || {}
    let obj = {}
    searchMap.jobnumber ? obj["jobnumber"] = searchMap.jobnumber : obj
    searchMap.name ? obj["name"] = searchMap.name : obj
    searchMap.role ? obj["role"] = searchMap.role : obj
    searchMap.entrydate ? obj["entrydate"] = searchMap.entrydate : obj
    Teacher.find(obj, (err, data) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "serve error getTeacherList"
            });
        }
        let count = data.length
        Teacher.find(obj).skip((page - 1) * parseInt(size)).limit(parseInt(size)).exec((err, teachers) => {
            if (err) {
                return res.status(200).json({
                    code: 3000,
                    flag: false,
                    message: "serve error getTeacherList"
                });
            }
            return res.status(200).json({
                code: 2000,
                flag: true,
                message: "查询成功",
                data: {
                    total: count,
                    rows: teachers
                }
            })
        })
    })
})

router.post("/teacher", (req, res) => {
    // console.log(req.body)
    new Teacher(req.body).save((err) => {
        if (err) {
            // console.log(err)
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "serve error addTeacher"
            });
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: "新增成功",

            // 'code': 2000,
            // 'flag': true,
            // 'message': "新增成功",
        })
    })
})
//根据id获取教师信息
router.get('/teacher', (req, res) => {
    Teacher.findById(req.query.id, (err, data) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "serve error getTeacherById"
            });
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: "查询id成功",
            data: data
        })
    })
})
//提交编辑教师数据
router.put('/teacher', (req, res) => {
    const id = req.body._id;
    Teacher.findByIdAndUpdate(id, req.body, (err, data) => {
        if (err) {
            // console.log(err)
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "serve error putTeacher"
            });
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: "修改教师信息成功",
            data: data
        })
    })
})
//删除教师
router.delete('/teacher', (req, res) => {
    Teacher.findByIdAndRemove(req.body.id, function (err) {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: "serve error deleteTeacher"
            });
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: "删除教师信息成功",
        })
    })
})
//获取学生列表，带分页项
router.post('/students/list', (req, res) => {
    // console.log(req.body);
    let page = req.body.page || 1;
    let size = req.body.size || 20;
    let searchMap = req.body.searchMap || {};
    let obj = {};
    searchMap.stunum ? obj['stunum'] = searchMap.stunum : obj;
    searchMap.name ? obj['name'] = searchMap.name : obj;
    searchMap.admissiondatteacher ? obj['admissiondatteacher'] = searchMap.admissiondatteacher : obj;
    searchMap.teacher ? obj['teacher'] = searchMap.teacher : obj;
    searchMap.class ? obj['class'] = searchMap.class : obj;
    Student.find(obj, (err, data) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: '查询失败'
            })
        }
        let count = data.length
        Student.find(obj).skip((page - 1) * parseInt(size)).limit(parseInt(size)).exec((err, students) => {
            if (err) {
                return res.status(200).json({
                    code: 3000,
                    flag: false,
                    message: '查询失败'
                })
            }
            return res.status(200).json({
                code: 2000,
                flag: true,
                message: '查询学员列表成功',
                data: {
                    total: count,
                    rows: students
                }
            })
        })

    })
})
//新增学生
router.post('/students', (req, res) => {
    new Student(req.body).save(function (err) {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: '新增学生失败'
            })
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: '新增学生成功'
        })
    })
})
//根据ID修改学员
router.get('/students', (req, res) => {
    Student.findById(req.query.id, (err, data) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: '修改学员失败'
            })
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: '修改学员成功',
            data: data
        })
    })
})
//根据ID修改学员信息
router.put('/students', (req, res) => {
    const id = req.body._id;
    Student.findByIdAndUpdate(id, req.body, (err) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: '修改学员信息失败'
            })
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: '修改学员信息成功'
        })
    })
})
//删除学员
router.delete('/students', (req, res) => {
    Student.findByIdAndRemove(req.body.id, err => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: '删除学员信息失败'
            })
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: '删除学员信息成功'
        })
    })
})
//校验密码是否正确
router.post('/user/pwd', (req, res) => {
    const body = req.body;
    User.findOne({
        _id: body.userId,
        password: body.password
    }, (err, data) => {
        if (err) {
            return res.status(200).json({
                code: 3000,
                flag: false,
                message: 'server error pwd'
            })
        }
        if (!data) {
            return res.status(200).json({
                code: 4000,
                flag: false,
                message: '密码不正确'
            })
        }
        return res.status(200).json({
            code: 2000,
            flag: true,
            message: '密码正确'
        })
    })
})
//修改密码
router.put('/user/pwd', (req, res) => {
    const id = req.body.userId;
    User.findOne({
        _id: id
    }, (err, data) => {
        if (err) {
            return res.status(500).json({
                code: 3000,
                flag: false,
                message: 'server error'
            })
        }
        if (!data) {
            return res.status(200).json({
                code: 4000,
                flag: false,
                message: '密码不正确'
            })
        }
        data.password = req.body.password;
        User.findByIdAndUpdate(id, data, (err) => {
            if (err) {
                return res.status(200).json({
                    code: 3000,
                    flag: false,
                    message: 'server error ped update'
                })
            }
            return res.status(200).json({
                code: 2000,
                flag: true,
                message: '修改成功'
            })
        })
    })
})
module.exports = router